package cn.softgame.jserver.connector.tcp;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

import cn.softgame.jserver.SocketHelper;

public class TCPHandler implements Runnable{

	private static String module = TCPHandler.class.getName();
	private SocketChannel sc;
	private SelectionKey sk;
	private SocketHelper socketHelper;
	private final static int READING=0;
	private final static int SENDING=1;
	private int state = READING;
	
	public TCPHandler(SelectionKey sk,SocketChannel sc){
		this.sc=sc;
		this.sk=sk;
		socketHelper = new SocketHelper();
		System.out.println("SocketReadHandler prepare ..."+module);
	}
	
	@Override
	public void run() {
		try {
			System.out.println("Handler running ..."+module);
			if(state==READING)
				read();
			else if(state==SENDING)
				send();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("readRequest error:"+module);
			socketHelper.close(sc);
			sk.cancel();
		}
	}
	
	private void read() throws Exception {
		byte[] bytes = socketHelper.readSocket(sc);
		if(bytes.length==0)
			throw new Exception();
		
		//实现服务器聊天核心处理功能，这里暂时打印出来，方便测试
		System.out.println(" read result is :" + new String(bytes));
		state=SENDING;
		sk.interestOps(SelectionKey.OP_WRITE);
	}

	private void send() throws IOException{
		String req1 = "come back";
		System.out.println(" send result is:"+req1);
		socketHelper.writeSocket(req1.getBytes(),sc);
		state=READING;
		sk.interestOps(SelectionKey.OP_READ);
	}
}
